package com.ucombuy.coupon.filter;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by yaosheng on 2021/3/2.
 * 限流过滤器处理类
 */
@Slf4j
@Component
@SuppressWarnings ("all")
public class RateLimiterFilter extends AbstractPreZuulFilter{

    //每秒可以获取到两个令牌（Google Guava提供）
    RateLimiter rateLimiter = RateLimiter.create (2.0);

    @Override
    protected Object cRun() {

        HttpServletRequest request = context.getRequest ();
        if(rateLimiter.tryAcquire ()){
            log.info ("Get rate token success");
            return Success ();
        }else{
            log.error ("rate limit : {}",request.getRequestURI ());
            return fail (402,"error : rate limit");
        }
    }

    @Override
    public int filterOrder() {
        return 2;
    }
}
